<template>
  <div class="container">
    <div v-if="loaded && !list.length" class="emptyarea">
      <div class="title">
        购物车快饿瘪了！
      </div>
      <div class="tip">
        快给我挑点宝贝
      </div>
      <router-link class="gotopicker" tag="div" to="/shop">
        去逛逛
      </router-link>
    </div>
    <div v-else-if="loaded">
      <div class="cart-item" v-for="(shop,indx) in list" :key="indx">
        <div class="p1 border-b">
          <div class="flex">
            <img @click="toggleShopSelected(shop,indx)" v-if="shop.selected" src="../../assets/icons/bill/selected@2x.png" alt="" class="selected-img">
            <img @click="toggleShopSelected(shop,indx)" v-else src="../../assets/icons/bill/notselected@2x.png" alt="" class="selected-img">
            <div class="flex-con shop-name">
              {{shop.providerName||'中油BP'}}
            </div>
          </div>
        </div>
        <div class="p2" v-for="(item,itemindex) in shop.items" :key="item.id">
          <mt-cell-swipe class="cell-swipe" :right="[
          {
            content: '删除',
            style: { background: 'red', color: '#fff'},
            handler: () => deleteCartItem(item.id,itemindex,indx) 
          }
        ]">
            <div class="flex">
              <img @click.stop="toggleItemSelected(item,itemindex,shop,indx)" v-if="item.selected" src="../../assets/icons/bill/selected@2x.png"
                alt="" class="selected-img">
              <img @click.stop="toggleItemSelected(item,itemindex,shop,indx)" v-else src="../../assets/icons/bill/notselected@2x.png" alt=""
                class="selected-img">
              <div class="item-cover bg-img-contained" :style="'background-image:url('+ (imgUrl(item.goodsCover))  +')'"></div>
              <div class="goods-info flex-con">
                <div class="goods-title">
                  {{item.goodsTitle}}
                </div>
                <div class="goods-rule" v-if="item.goodsRules">
                  规格：{{item.goodsRules}}
                </div>
                <div class="flex">
                  <div class="flex-con">
                    <span class="points">{{item.points}}积分</span>
                    <span class="money">+{{item.price}}元</span>
                  </div>
                  <div class="clearfix">
                    <div class="reducenum-btn" :class="{'item-num-disabled':item.num<=1}" @click.stop="reduceItemNum(item)">-</div>
                    <input type="number" class="goods-num" :value="item.num" @input="setItemNum(item)">
                    <div class="addnum-btn" @click.stop="addItemNum(item)">+</div>
                  </div>
                </div>
              </div>
            </div>
          </mt-cell-swipe>

        </div>

      </div>
      <div class="footer-nav-before"></div>
      <div class="footer-nav flex">
        <div class="flex-con">
          <div class="cal-info">
            <div class="flex">
              <div class="flex" @click.stop="toggleAllSelected">
                <div>
                  <img v-if="allSelected" src="../../assets/icons/bill/selected@2x.png" alt="" class="selected-img">
                  <img v-else src="../../assets/icons/bill/notselected@2x.png" alt="" class="selected-img">
                </div>

                <div>全选</div>
              </div>
              <div class="flex-con text-right">
                合计:
                <span class="points">{{points}}积分</span>
                <span class="money">+{{money}}元</span>
              </div>
            </div>
          </div>
        </div>
        <div class="calbtn" @click="gotoSureBill" :class="{'calbtn-disabled':selectedCount==0}">
          去结算（{{selectedCount}}）
        </div>
      </div>
    </div>

  </div>
</template>
<script>
export default {
  mounted() {
    this.showLoading();
    this.$get("/api/user/getCart")
      .then(info => {
        this.loaded = true;
        this.hideLoading();
        info = info || [];
        if (info.length) {
          let map = {};
          for (let item of info) {
            if (!map[item.providerId]) {
              map[item.providerId] = {
                items: [],
                providerName: item.providerName
              };
            }
            map[item.providerId].items.push(item);
          }
          for (let key in map) {
            this.list.push(map[key]);
          }
        }
      })
      .catch(() => {
        this.hideLoading();
      });
  },
  methods: {
    reduceItemNum(item) {
      if (item.num > 1) {
        item.num--;
        this.setItemNum(item);
      }
    },
    toggleShopSelected(shop, idx) {
      shop.selected = !shop.selected;
      for (let i = 0; i < shop.items.length; i++) {
        shop.items[i].selected = shop.selected;
      }
      this.allSelected = this.list.every(shop => shop.selected);
      this.$set(this.list, idx, shop);
      this.calSum();
    },
    toggleAllSelected() {
      this.allSelected = !this.allSelected;
      this.list.forEach(el => {
        el.selected = this.allSelected;
        el.items.forEach(i => {
          i.selected = el.selected;
        });
      });
      this.calSum();
    },
    toggleItemSelected(item, itemindex, shop, shopindex) {
      item.selected = !item.selected;
      shop[itemindex] = item;
      this.list[shopindex] = shop;
      shop.selected = shop.items.every(el => el.selected);
      this.allSelected = this.list.every(shop => shop.selected);
      this.$set(this.list, shopindex, shop);
      this.calSum();
    },
    addItemNum(item) {
      item.prevNum = item.num;
      item.num++;
      this.setItemNum(item);
    },
    setItemNum(item) {
      if (item.selected) {
        this.calSum();
      }
      this.$post("/api/user/setCartItemNum", {
        id: item.id,
        num: item.num
      })
        .then(_ => {})
        .catch(_ => {
          if (item.prevNum) {
            item.num = item.prevNum;
          }
        });
    },
    calSum() {
      let points = 0;
      let price = 0;
      let num = 0;
      this.list.forEach(shop => {
        shop.items.forEach(item => {
          if (item.selected) {
            points += item.points * item.num;
            price += item.price * item.num;
            num += item.num;
          }
        });
      });
      this.points = points;
      this.selectedCount = num;
      this.money = Math.round(price * 100) / 100;
    },
    deleteCartItem(id, itemindex, shopindx) {
      // console.log(this.list[shopindx].items)
      this.$messagebox
        .confirm("确定移出该商品吗?")
        .then(action => {
          this.$post("/api/user/removeCartItem", {
            id
          }).then(el => {
            this.list[shopindx].items.splice(itemindex, 1);
            if (this.list[shopindx].items.length == 0) {
              this.list.splice(shopindx, 1);
            }
          });
        })
        .catch(el => {});
    },
    gotoSureBill() {
      if (this.selectedCount) {
        let selectedCartIds = [];
        this.list.forEach(shop => {
          shop.items.forEach(item => {
            if (item.selected) {
              selectedCartIds.push(item.id);
            }
          });
        });
        this.$router.push(
          "/surebill/" + encodeURIComponent(selectedCartIds.join(","))
        );
      }
    }
  },
  data() {
    return {
      allSelected: false,
      selectedCount: 0,
      loaded: false,
      points: 0,
      money: 0,
      list: []
    };
  }
};
</script>

<style lang="scss" scoped>
html,
body,
.container {
  background-color: #f1f0f0;
  font-size: 0.3733rem;
}

.footer-nav-before {
  height: 1.2267rem;
}

.calbtn-disabled {
  opacity: 0.4;
}

.cart-item {
  background-color: #fff;
  margin-bottom: 0.2rem;
}

.selected-img {
  width: 0.44rem;
  height: 0.44rem;
  margin-right: 0.2667rem;
}

.footer-nav {
  height: 1.2267rem;
  position: fixed;
  background-color: #fff;
  left: 0;
  right: 0;
  bottom: 0;
}

.item-cover {
  width: 3.2667rem;
  height: 2.1733rem;
}

.p2 {
  padding: 0.36rem 0.4rem;
}

.p1 {
  padding: 0.32rem 0.4rem;
  font-size: 0.32rem;
}

.calbtn {
  width: 3.16rem;
  line-height: 1.2267rem;
  text-align: center;
  background-color: #e82f24;
  font-size: 0.4rem;
  color: #ffffff;
}

.cal-info {
  padding-left: 0.4rem;
  padding-right: 0.2933rem;
}

.goods-info {
  padding-left: 0.32rem;
  .goods-rule {
    font-size: 0.2933rem;
    color: #17402a;
    padding-bottom: 0.4rem;
  }
}

.goods-title {
  font-size: 0.3467rem;
  line-height: 1.2em;
  padding-bottom: 0.3733rem;
  color: #17402a;
}

.points {
  font-size: 0.3733rem;
  color: #ff2a2a;
}

.money {
  font-size: 0.3733rem;
  color: #005a1a;
}

.reducenum-btn,
.goods-num,
.addnum-btn {
  float: left;
}

.goods-num {
  width: 0.76rem;
  text-align: center;
  font-size: 0.3733rem;
  padding: 0;
  border: none;
  margin: 0;
  display: inline-block;
  height: auto;
}

.reducenum-btn,
.addnum-btn {
  text-align: center;
  width: 0.4667rem;
  color: white;
  font-size: 0.49rem;
  height: 0.4667rem;
  border-radius: 0.08rem;
  background-color: #34a359;
}

.item-num-disabled {
  background-color: rgba(52, 163, 89, 0.5);
}

.addnum-btn {
  background-color: #34a359;
}

.emptyarea {
  padding-top: 1.4267rem;
  text-align: center;
  .title {
    font-size: 0.52rem;
    color: #333333;
    padding-bottom: 0.52rem;
  }
  .tip {
    color: #666666;
    font-size: 0.3867rem;
  }
  .gotopicker {
    width: 3.8667rem;
    height: 1.1067rem;
    line-height: 1.1067rem;
    text-align: center;
    border: 1px solid #ff2a2a;
    border-radius: 0.1333rem;
    color: #ff2a2a;
    font-size: 0.4rem;
    margin: 0 auto;
    margin-top: 1.12rem;
  }
}
</style>
